import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'

// 创建axios实例
const instance = axios.create({
  baseURL: 'https://interview-api-t.itheima.net',
  timeout: 3000,
  headers: { 'X-Custom-Header': 'foobar' }
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 从store获取token
    const token = store.state.user.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    // 处理401未授权错误
    if (error.response && error.response.status === 401) {
      // 清除token并跳转登录页
      store.commit('user/clearToken')
      Message.error('登录已过期，请重新登录')
      router.replace('/login')
    }
    return Promise.reject(error)
  }
)

export default instance
